package com.pan.service.impl;

import com.pan.annotation.EntityNotNull;
import com.pan.annotation.RecordHistory;
import com.pan.annotation.UpdateStatusCheck;
import com.pan.dao.order1.OrderTable1SelectDao;
import com.pan.dao.order1.OrderTable1UpdateDao;
import com.pan.dao.order2.OrderTable2SelectDao;
import com.pan.dao.order2.OrderTable2UpdateDao;
import com.pan.entity.Result;
import com.pan.enume.EntityEnum;
import com.pan.enume.HistoryEnum;
import com.pan.enume.ResultEnum;
import com.pan.service.OrderSelectService;
import com.pan.service.OrderUpdateService;
import com.pan.tools.RedisTools;
import com.pan.vo.ChildOrder;
import com.pan.vo.OrderVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.Predicate;

@Service("orderUpdateService")
public class OrderUpdateServiceImpl implements OrderUpdateService {

    @Resource
    private OrderSelectService orderSelectService;

    @Resource
    private RedisTools redisTools;

    @Resource
    private OrderTable1UpdateDao orderTable1UpdateDao;

    @Resource
    private OrderTable2SelectDao orderTable2SelectDao;

    @Resource
    private OrderTable2UpdateDao orderTable2UpdateDao;

    @Override
    @EntityNotNull(daoClass = OrderTable1SelectDao.class,idName = "order1Id")
    @UpdateStatusCheck(entity = EntityEnum.ORDER_1,idName = "order1Id")
    @RecordHistory(value = HistoryEnum.ORDER_1,idName = "order1Id")
    public Result updateOrder1Status(String ticket,Long order1Id,Integer status)  {
        Result<OrderVo> orderResult = orderSelectService.selectAllInfoById(order1Id);
        OrderVo orderVo = orderResult.getData();
        if (status!=0&&status!= orderVo.getOrder1Status()+1){
            return new Result(403,"修改失败");
        }
        List<ChildOrder> childOrder = orderVo.getChildOrders();
        Predicate<ChildOrder> isNoStatus = orderTable2 -> {
            Integer order2Status = orderTable2.getOrder2Status();
            return order2Status==status||order2Status==4||order2Status==5?false:true;
        };
        if (childOrder.stream().anyMatch(isNoStatus)){
            return new Result(403,"修改失败，子订单状态不一致");
        }
        orderTable1UpdateDao.updateOrder1Status(order1Id,status);
        return new Result(200,"修改成功");
    }

    @Override
    @EntityNotNull(daoClass = OrderTable2SelectDao.class,idName = "order2Id")
    @UpdateStatusCheck(entity = EntityEnum.ORDER_2,idName = "order2Id")
    @RecordHistory(value = HistoryEnum.ORDER_2,idName = "order2Id")
    public Result updateOrder2Status(String ticket, Long order2Id, Integer status){
        orderTable2UpdateDao.updateOrder2Status(order2Id,status);
        return new Result(ResultEnum.SUCCESS);
    }


}
